﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CSharp.Infrastructure
{
    public class CVSHelper
    {
        public static List<T> ReadCVS<T>(byte[] data, Encoding encode) where T : class, new()
        {
            var ps = typeof(T).GetProperties();

            List<T> result = new List<T>();
            bool is_column = false;
            List<Tuple<string, int>> col_list = new List<Tuple<string, int>>();
            // 从 data中解析内容
            List<byte> dt = new List<byte>();
            for (int i = 0; i < data.Length - 1; i++)
            {
                if (data[i] == encode.GetBytes(new char[] { '\r' })[0] && data[i + 1] == encode.GetBytes(new char[] { '\n' })[0] || i == data.Length - 2)
                {
                    if (i == data.Length - 2)
                    {
                        dt.Add(data[i]);
                        i++;
                    }
                    else
                    {
                        i += 2;
                    }

                    var str = encode.GetString(dt.ToArray());
                    dt = new List<byte>();

                    var array = CSVstrToArry(str);
                    if (!is_column)
                    {
                        for (int j = 0; j < array.Length; j++)
                        {
                            col_list.Add(Tuple.Create(array[j].Trim(), j));
                        }

                        is_column = true;
                    }
                    else
                    {
                        T t = new T();
                        foreach (var p in ps)
                        {
                            var att_info = p.GetCustomAttributesData().ToList().Find(a => a.AttributeType == typeof(DescriptionAttribute));
                            if (att_info != null)
                            {
                                var item = col_list.Find(a => a.Item1 == att_info.ConstructorArguments[0].Value as string);
                                if (item == null)
                                {
                                    continue;
                                }

                                var val = array[item.Item2].Trim();
                                if (p.PropertyType == typeof(double))
                                {
                                    double.TryParse(val, out var d);
                                    p.SetValue(t, d, null);
                                }
                                else if (p.PropertyType == typeof(int))
                                {
                                    int.TryParse(val, out var d);
                                    p.SetValue(t, d, null);
                                }
                                else
                                {
                                    p.SetValue(t, val, null);
                                }
                            }
                        }

                        result.Add(t);
                    }
                }

                if (i < data.Length - 1)
                {
                    dt.Add(data[i]);
                }
            }

            return result;
        }

        /// <summary>
        /// 跳过引号中的逗号,进行逗号分隔(字段内容中的逗号不参与分隔)
        /// </summary>
        /// <param name="strLine"></param>
        /// <returns></returns>
        private static string[] CSVstrToArry(string splitStr)
        {
            var newstr = string.Empty;
            List<string> sList = new List<string>();

            bool isSplice = false;
            string[] array = splitStr.Split(new char[] { ',' });
            foreach (var str in array)
            {
                if (!string.IsNullOrEmpty(str) && str.IndexOf('"') > -1)
                {
                    var firstchar = str.Substring(0, 1);
                    var lastchar = string.Empty;
                    if (str.Length > 0)
                    {
                        lastchar = str.Substring(str.Length - 1, 1);
                    }
                    if (firstchar.Equals("\"") && !lastchar.Equals("\""))
                    {
                        isSplice = true;
                    }
                    if (lastchar.Equals("\""))
                    {
                        if (!isSplice)
                            newstr += str;
                        else
                            newstr = newstr + "," + str;

                        isSplice = false;
                    }
                }
                else
                {
                    if (string.IsNullOrEmpty(newstr))
                        newstr += str;
                }

                if (isSplice)
                {
                    //添加因拆分时丢失的逗号
                    if (string.IsNullOrEmpty(newstr))
                        newstr += str;
                    else
                        newstr = newstr + "," + str;
                }
                else
                {
                    sList.Add(newstr.Replace("\"", "").Trim());//去除字符中的双引号和首尾空格
                    newstr = string.Empty;
                }
            }

            return sList.ToArray();
        }
    }
}
